package com.example.logisticsingle.authorization;



import com.example.logisticsingle.Service.LoginService;
import com.example.logisticsingle.String.StringUtils;
import com.example.logisticsingle.constants.Config;
import com.example.logisticsingle.constants.ResponseEnum;
import com.example.logisticsingle.dto.Result;
import com.example.logisticsingle.exception.UserDisabledException;
import com.example.logisticsingle.model.LoginLog;
import com.example.logisticsingle.requsest.ClinetRequestInfo;
import com.example.logisticsingle.requsest.IPDetail;
import com.example.logisticsingle.requsest.RequestUtils;
import com.example.logisticsingle.utils.JsonUtils;
import com.example.logisticsingle.utils.ResultUtils;
import eu.bitwalker.useragentutils.DeviceType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * 登录失败处理

 *
 */
@Component
@Slf4j
public class FailureAuthenticationHandler implements AuthenticationFailureHandler {
    @Autowired
    private LoginService loginService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        log.info("登录失败:{}",exception.getMessage());
        String str = request.getHeader(Config.REQUEST_TYPE);
        String request_type = StringUtils.isNull(str)?request.getParameter(Config.REQUEST_TYPE):str;
        //记录日志

        LoginLog loginLog = new LoginLog();
        loginLog.setUserName(request.getParameter("username"));
        loginLog.setLoginTime(new Date());
        loginLog.setStatus("1");
        if(StringUtils.isNotNull(request_type) && Integer.valueOf(request_type)==Config.REQUEST_TYPE_WEB)
        {
    ClinetRequestInfo clinetRequestInfo = RequestUtils.getClinetRequestInfo(request);
            if(null!=clinetRequestInfo) {
                loginLog.setBrowser(String.format("%s %s", clinetRequestInfo.getBrowserInfo().getName(),clinetRequestInfo.getBrowserVersion()));
                loginLog.setIpaddr(clinetRequestInfo.getIpInfo().getIp());
                loginLog.setLoginLocation(clinetRequestInfo.getIpInfo().getDesc());
                loginLog.setOs(clinetRequestInfo.getOsInfo().getName());
            }
            loginLog.setMsg("登录失败");
            log.info("insert login log:{}",loginLog);
            loginService.insertLoginLog(loginLog);
            String url = request.getContextPath()+"/login?errorMsg="+ URLEncoder.encode(exception.getMessage(),"UTF-8");
            String redit_url = request.getParameter(Config.REDIRECT_URL);
            url = StringUtils.isNotNull(redit_url)?String.format("%s&%s=%s",url,Config.REDIRECT_URL,redit_url):url;
            response.setContentType("application/html;charset=UTF-8");
            response.sendRedirect(url);
        }else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.setContentType("application/json;charset=UTF-8");
            Result<?> result = null;
            if(exception instanceof UserDisabledException){
                result = ResultUtils.failure(ResponseEnum.USER_DISABLED);
            }else if(exception instanceof UsernameNotFoundException) {
                result = ResultUtils.failure(ResponseEnum.LOGIN_ACCOUNT_FAIL);
            }else if(exception instanceof BadCredentialsException) {
                result = ResultUtils.failure(ResponseEnum.LOGIN_PASSWORD_FAIL);
            }else {
                result = ResultUtils.failure(ResponseEnum.LOGIN_FAIL);
            }
            String agent = request.getHeader(Config.REQUEST_USER_AGENT);
            agent = StringUtils.isNull(agent)?request.getHeader("User-Agent"):agent;
            String ip = request.getHeader(Config.REQUEST_IP);
            ip = StringUtils.isNull(ip)?RequestUtils.getIPAddress(request):ip;
            loginLog.setIpaddr(ip);
            ClinetRequestInfo clinetRequestInfo = RequestUtils.getClinetRequestInfo(agent,ip);
            if(null!=clinetRequestInfo) {
                loginLog.setBrowser(String.format("%s %s", clinetRequestInfo.getBrowserInfo().getName(),clinetRequestInfo.getBrowserVersion()));
                loginLog.setLoginLocation(clinetRequestInfo.getIpInfo().getDesc());
                loginLog.setOs(clinetRequestInfo.getOsInfo().getName());
                if(clinetRequestInfo.getDeviceType().equals(DeviceType.MOBILE.getName())) {
                    loginLog.setPhoneBrand(clinetRequestInfo.getMobileBrand());
                    loginLog.setPhoneModel(clinetRequestInfo.getMobileModel());
                    loginLog.setPhoneOs(clinetRequestInfo.getOsInfo().getName());
                }
            }else {
                IPDetail ipDetail = RequestUtils.getIpDetailInfo(ip);
                if(null != ipDetail)
                    loginLog.setLoginLocation(ipDetail.getDesc());
            }
            loginLog.setMsg(result.getMessage());
            log.info("insert login log:{}",loginLog);
            loginService.insertLoginLog(loginLog);
            response.getWriter().write(JsonUtils.toJson(result));
        }


    }

}
